import { statSync, readdirSync } from 'fs';
import { resolve } from 'path';

export default (options = {}) => {
  // 拦截http请求
  // 当我们用fetch或axios去请求时
  // axios baseURL 请求地址
  // 当打给本地的开发服务器的时候 viteserver服务器接管
  return {
    configureServer: async(server) => {
      const mockPath = options.mockPath ?? 'mock'; // 获得options里的mockPath
      const mockStat = statSync(mockPath);
      let mockResult = []
      if (mockStat.isDirectory()) { // 确定是目录
        let children = readdirSync(mockPath);
        const result = await import(resolve(process.cwd(), mockPath, children[0]))
        mockResult = result.default;
      }
      // 服务器的相关配置
      /**
       * @req 请求对象 用户发过来的请求，请求头、请求体、地址、cookie
       * @res 响应对象 res.header
       * @next 是否交给下个中间件，调用next方法会将处理结果交给下一个中间件
       */
      server.middlewares.use(async (req, res, next) => {
        // 自定义请求处理...
        // console.log('req', req.url);
        // console.log('res', res);
        const matchItem = mockResult.find(mockDescriptor => mockDescriptor.url === req.url);
        if (matchItem) {
          const responseData = matchItem.response(req);
          res.setHeader('Content-Type', 'application/json');
          res.end(JSON.stringify(responseData)); // 设置请求头, 异步
        } else {
          next();
        }
      })
    }
  }
}